{% extends "base.html" %}


{% block head %}
   <style type="text/css">
   .info-content {
          position: relative;
          background-color: #BDE5F8;
          border: 1px solid #999999;
          border: 1px solid rgba(0, 0, 0, 0.2);
          border-radius: 6px;
          outline: none;
          -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
                  box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
          background-clip: padding-box;
      }
   .error-content {
          position: relative;
          background-color: #FFBABA;
          border: 1px solid #999999;
          border: 1px solid rgba(0, 0, 0, 0.2);
          border-radius: 6px;
          outline: none;
          -webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
                  box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
          background-clip: padding-box;
      }

    </style>
    <script>
    $(document).ready(function(){

{% with OKs = get_flashed_messages(category_filter=["ok"]) %}
{% if OKs %}
    {% for msg in OKs %}
    show_info_refresh("OK","{{ msg }}")
    {% endfor %}
{% endif %}
{% endwith %}

{% with Errors = get_flashed_messages(category_filter=["error"]) %}
{% if Errors %}
    {% for msg in Errors %}
    show_error_refresh("Error","{{ msg }}")
    {% endfor %}
{% endif %}
{% endwith %}


    });



    function edit() {
            loginname= $.trim($("#loginname").val())
            if (loginname =="") {
                alert("loginname can't be empty")
                return false
            }
            check_password()
            password=$.trim($("#password1").val())
            realname= $.trim($("#realname").val())
            if (realname =="") {
                alert("realname can't be empty")
                return false
            }
            check_phonenumber()
            phonenumber=$.trim($("#phonenumber").val())
            check_email()
            email=$.trim($("#email").val())

            var cluster_array= new Array()
            $("input[name='checked_cluster']:checkbox:checked").each(function(){
                cluster_array.push($(this).val())
            });
            cluster_list=cluster_array.join(',');

        $.post("/edit_user/"+$('#edit').attr('userid'),
        {
            csrf_token:"{{ csrf_token() }}",
            loginname:loginname,
            password:password,
            realname:realname,
            phonenumber:phonenumber,
            email:email,
            comment:$("#comment").val(),
            is_admin:$("#is_admin").is(':checked'),
            is_locked:$("#is_locked").is(':checked'),
            permit_clusters:cluster_list
        },
        function(data,status){
            content= data;
            $('#addModal').modal('hide')
            if (content == "success"){
               show_info_refresh("ok","Edited successfully");
            }
            else if( content.match("user  not found")){
                show_error_refresh("error",content)
            }
            else{
                show_error_refresh("unknown error","Please check the server's log")
            }
         });
        }


    function show_edit(id,loginname,realname,phonenumber,email,is_admin,is_locked,managed,commentid){
        $('#add').attr('id','edit')
        $("#loginname").attr("value",loginname) ;
        $("#password1").attr("value","not_modified")
        $("#password2").attr("value","not_modified")
        $("#realname").attr("value",realname) ;
        $('#phonenumber').attr("value",phonenumber)
        $('#email').attr("value",email)
        if (is_admin == "True"){
             document.getElementById('is_admin').checked=true;
        }
        else{
            document.getElementById('is_admin').checked=false;
        }
        if (is_locked == "True"){
             document.getElementById('is_locked').checked=true;
        }
        else{
            document.getElementById('is_locked').checked=false;
        }
        comment=$(commentid).text();
        $("input[name='checked_cluster']").each(function(){this.checked = false;})
        managed=managed.split(",")
        managed.pop()
        for (var i=0;i< managed.length;i++){
            document.getElementById("cluster"+managed[i]).checked=true;
        }
        $("#comment").text(comment) ;
        $("#addModalLabel").text("Edit a  User")
        $('#edit').attr('userid',id);
        $('#edit').text('Save changes');
        $('#edit').attr("onclick","edit()")
        $('#addModal').modal('show');
    }

    function show_add(){
        $('#edit').attr('id','add')
        $("#loginname").attr("value","") ;
        $("#realname").attr("value","") ;
        $("#phonenumber").attr("value","") ;
        $("#email").attr("value","") ;
        document.getElementById('is_admin').checked=false;
        document.getElementById('is_locked').checked=true;
        $("input[name='checked_cluster']").each(function(){this.checked = false;})
        $("#comment").text("") ;
        $("#addModalLabel").text("Add a  User")
        $('#add').text('Add this User')
        $('#add').attr("onclick","register()")
        $('#addModal').modal('show');
    }


    function show_info_refresh(title,info) {
            $("#myinfoLabel_refresh").text(title) ;
            $("#myinfoContent_refresh").text(info) ;
            $(".error-content").addClass("info-content")
            $(".info-content").removeClass("error-content")
            $('#myinfo_refresh').modal({ keyboard: true });
    }
    function show_error_refresh(title,error) {
            $("#myinfoLabel_refresh").text(title) ;
            $("#myinfoContent_refresh").text(error) ;
            $(".info-content").addClass("error-content")
            $(".error-content").removeClass("info-content")
            $('#myinfo_refresh').modal({ keyboard: true });
    }
    function delete_confirm(id){
        if(confirm("Really want to delete this user ?")){
            location.href='/delete_one_user/'+id
        }
    }
    function check_password(){
            password1=$("#password1").val();
            password2=$("#password2").val();
            if (password1 != password2) {
                alert("first password and second password are not identical");
                $('#g_password1').addClass("has-error");
                return false
            }
            else {
            if($('#g_password1').hasClass("has-error"))
            {
                $('#g_password1').removeClass("has-error");
            }
            return true;
            }
    }
    function check_phonenumber(){
            phonenumber=$("#phonenumber").val()
            if (phonenumber == ""){
                alert("phone number can't be empty")
                return false
            }
            if (!phonenumber.match(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|170)+\d{8})$/)) {
                alert("Your Phone Number seems not in China");
                 $('#g_phonenumber').addClass("has-error");
                return false;
                }
            else {
              if($('#g_phonenumber').hasClass("has-error"))
            {
                $('#g_phonenumber').removeClass("has-error");
            }
            return true;
            }
        }
    function check_email(){
            email=$("#email").val()
            if (email == ""){
                alert("E-mail can't be empty")
                return false
            }
            if (!email.match(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/)) {
            alert("It seems to be a wrong Email");
            $('#g_email').addClass("has-error");
            return false;
            }
            else {
              if($('#g_email').hasClass("has-error"))
            {
                $('#g_email').removeClass("has-error");
            }
            return true;
            }

        }
    function register() {
            loginname= $.trim($("#loginname").val())
            if (loginname =="") {
                alert("loginname can't be empty")
                return false
            }
            check_password()
            password=$.trim($("#password1").val())
            realname= $.trim($("#realname").val())
            if (realname =="") {
                alert("realname can't be empty")
                return false
            }
            check_phonenumber()
            phonenumber=$.trim($("#phonenumber").val())
            check_email()
            email=$.trim($("#email").val())

            var cluster_array= new Array()
            $("input[name='checked_cluster']:checkbox:checked").each(function(){
                cluster_array.push($(this).val())
            });
            cluster_list=cluster_array.join(',');

             $.post("/register",
        {
            csrf_token:"{{ csrf_token() }}",
            loginname:loginname,
            password:password,
            realname:realname,
            phonenumber:phonenumber,
            email:email,
            comment:$("#comment").val(),
            is_admin:$("#is_admin").is(':checked'),
            is_locked:$("#is_locked").is(':checked'),
            permit_clusters:cluster_list
        },
        function(data,status){
            content= data;
            $('#addModal').modal('hide')
            if (content == "success"){
               show_info_refresh("ok","Register successfully");
            }
            else if( content.match("is already exist in database")){
                show_error_refresh("error",content)
            }
            else{
                show_error_refresh("unknown error","Please check the server's log");
            }
         });
        }
        function check_login_loginnamne(){
            loginname= $.trim($("#loginloginname").val())
            if (loginname =="") {
                alert("loginname can't be empty")
                return false
            }
        }
        function check_login_password() {
            password=$.trim($("#loginpassword").val())
            if (password =="") {
                alert("password can't be empty")
                return false
            }
        }

    </script>

    <style type="text/css">
    .btn-lg {

        float: right;
        padding: 10px 16px;
        font-size: 18px;
        line-height: 1.33;
        border-radius: 6px;
        }
    .Textarea {
        width:100%;
    }

</style>

{% endblock %}


        {% block body%}



 <div class="container">

     <h1>manage the users</h1>


      <table class="table table-hover">
        <thead>
          <tr>
            <th>Login Name</th>
            <th>Real Name</th>
            <th>is locked</th>
            <th>is admin</th>
            <th>Phone Number</th>
            <th>Email</th>
            <th>edit</th>
            <th>delete</th>
          </tr>
        </thead>
        <tbody>
        {% for user in users.items %}
          <tr data-toggle="tooltip" data-placement="top" title="{{ user.comment }}" id="tr{{ user.userid }}"  onmouseover="$('#tr{{ user.userid }}').tooltip('show')">
            <td style="display: none;" id="id{{ user.userid }}">{{ user.userid }}</td>
            <td style="display: none;" id="comment{{ user.userid }}">{{ user.comment }}</td>
            <td>{{ user.loginname }}</td>
            <td>{{ user.realname }}</td>
            <td>{{ user.is_locked }}</td>
            <td>{{ user.is_admin }}</td>
            <td>{{ user.phonenumber }}</td>
            <td>{{ user.email }}</td>
            <td><button type="button" class="btn btn-info" onclick="show_edit('{{ user.userid }}','{{ user.loginname }}','{{ user.realname }}','{{ user.phonenumber }}','{{ user.email }}','{{ user.is_admin }}','{{ user.is_locked }}','{% for i in user.managed.all() %}{{ i.clusterid }},{% endfor %}','#comment{{ user.userid }}')">&nbsp; edit &nbsp;</button></td>
            <td><button type="button" class="btn  btn-danger" onclick="delete_confirm({{ user.userid }})">delete</button></td>
          </tr>
        {%  endfor %}
        </tbody>
      </table>

 <ul class="pager">
      {% if users.has_prev %}<li><a href="{{ url_for('manage_users', page = users.prev_num) }}"><< Previous</a></li>{% else %}<li class="disabled"><a href="#"><< Previous</a></li>{% endif %} </li> |
      {% if users.has_next %}<li><a href="{{ url_for('manage_users', page = users.next_num) }}"> Next >></a></li>{% else %}<li class="disabled"><a href="#"> Next >></a></li>{% endif %}</li>
</ul>

 <!-- Button trigger modal -->
<button class="btn btn-primary btn-lg " data-toggle="modal" onclick="show_add()">
  Add a new user
</button>








<!-- Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="addModalLabel">Add a new User</h4>
      </div>
      <div class="modal-body">


<form method="post" action="" class="addhosts" name="form1">
    {{ registerform.csrf_token }}
    <!--{{ registerform.hidden_tag() }}-->

     <!--<div class="col-xs-3">-->

    <h5>start with "*" is required , others are optional</h5>



  <div class="input-group" id="g_loginname">
  <span class="input-group-addon">*  Login Name</span>
  {{registerform.loginname(class="form-control",placeholder="xiaosu")}}
   </div>


    <br>

   <div class="input-group" id="g_password1">
  <span class="input-group-addon">*  Password</span>
  <input class="form-control" id="password1" name="password1" placeholder="password" type="password">
   </div>

    <br>


   <div class="input-group" id="g_password2">
  <span class="input-group-addon">*  Repeat Password</span>
<input class="form-control" id="password2" name="password2" onblur="check_password()" placeholder="repeat password" type="password">
   </div>

    <br>
      <div class="input-group" id="g_realname">
  <span class="input-group-addon">*  Real Name</span>
  {{registerform.realname(class="form-control",placeholder="your real name")}}
   </div>


        <br>
   <div class="input-group" id="g_phonenumber">
  <span class="input-group-addon">*  Phone Number</span>
  {{registerform.phonenumber(class="form-control",placeholder="your mobile phone to recieve sms",onblur="check_phonenumber()")}}
   </div>

        <br>
      <div class="input-group" id="g_email">
  <span class="input-group-addon">*  E-mail</span>
  {{registerform.email(class="form-control",placeholder="your E-mail address",onblur="check_email()")}}
   </div>

    <div class="checkbox">
    <label>
      {{ registerform.is_admin }} Admin Privileges
    </label>
  </div>

    <div class="checkbox">
    <label>
      {{ registerform.is_locked }} Lock this account
    </label>
  </div>

    <br>
     <div class="input-group ">
  <span class="input-group-addon"> edit user's comment below :</span>

   </div>
           <textarea id="comment" class="form-control" wrap="wrap" rows="3"></textarea>

   <!--</div>-->
    <br>
    user's permission:
    <br>
    {% for cluster in clusters %}
        <input type="checkbox" name="checked_cluster" id="cluster{{ cluster.clusterid }}"  value="{{ cluster.clusterid }}">{{ cluster.clustername }} &nbsp;
    {% endfor %}
</form>



      </div>
      <div class="modal-footer">
        <button type="button" id="exit" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" id="edit" class="btn btn-primary" >Add this user</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div>








 <div id="myinfo_refresh" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myinfoContent" aria-hidden="true">
      <div class="modal-dialog">
        <div class="info-content">
          <div class="modal-header">
            <button type="button" onclick="window.location.reload()" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title" id="myinfoLabel_refresh">Modal Heading</h4>
          </div>
          <div class="modal-body">
            <h4 id="myinfoContent_refresh">Overflowing text </h4>
          </div>
          <div class="modal-footer">
            <button type="button" onclick="window.location.reload()"  class="btn btn-default" data-dismiss="modal">OK</button>
          </div>

        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->






        {% endblock %}